#include "sessionfriendarea.h"
#include "model/data.h"
#include "debug.h"
#include "model/datacenter.h"
#include "mainwidget.h"
#include <QScrollBar>
#include <QVBoxLayout>
#include <QPushButton>
#include <QLabel>
#include <QGridLayout>
#include <QStyleOption>
#include <QPainter>

using namespace model;

SessionFriendArea::SessionFriendArea(QWidget *parent)
    : QScrollArea{parent}
{
    //1.设置必要属性
    this->setWidgetResizable(true); //滚动属性
    //设置滚动条相关样式
    this->verticalScrollBar()->setStyleSheet("QScrollBar:vertical { width: 2px; background-color: rgb(46, 46, 46);}");
    this->horizontalScrollBar()->setStyleSheet("QScrollBar:horizontal { height: 0px; }");
    this->setStyleSheet("QScrollArea {border: none;}");
    //2. 把widget添加进来

    container = new QWidget();
    container->setFixedWidth(310);

    this->setWidget(container);

    //3. 给这个widget 指定布局管理器 添加元素
    QVBoxLayout* layout = new QVBoxLayout();
    layout->setContentsMargins(0, 0, 0, 0);
    layout->setSpacing(0);
    layout->setAlignment(Qt::AlignTop);
    container->setLayout(layout);


    //test
#if TEST_UI
    for(int i = 0; i < 30; i ++)
    {
        addItem(SessionItemType, QString::number(i),QIcon(":/resource/image/defaultAvatar.png"), "xiang" + QString::number(i), "hello");
    }
#endif

}

void SessionFriendArea::clear()
{
    QLayout* layout = container->layout();
    //遍历清空
    for(int i = layout->count() - 1; i >= 0; i--)
    {
        //删除
        QLayoutItem* item = layout->takeAt(i);
        // 释放
        if(item->widget())
            delete item->widget();
    }
}
// 添加的 不是SessionFriendItem了 添加的是SessionFriendItem的子类
//SessionItem FriendItem ApplyItem 其中一个
void SessionFriendArea::addItem(ItemType itemType, const QString& id, const QIcon &avatar, const QString &name, const QString &text)
{
    SessionFriendItem* item = nullptr;
    if(itemType == SessionItemType)
    {
        item = new SessionItem(this, id, avatar, name, text);
    }
    else if(itemType == FriendItemType)
    {
        item = new FriendItem(this, id, avatar, name, text);
    }
    else if(itemType == ApplyItemType)
    {
        item = new ApplyItem(this, id, avatar, name);
    }
    else
    {
        LOG() << "error itemType :" << itemType;
        return;
    }
    container->layout()->addWidget(item);
}

void SessionFriendArea::clickItem(int index)
{
    if(index < 0 || index > container->layout()->count())
    {
        LOG() << "点击元素的下标超出范围！ index = " << index;
        return;
    }
    QLayoutItem* layoutItem = container->layout()->itemAt(index);
    if(layoutItem == nullptr || layoutItem->widget() == nullptr)
    {
        LOG() << "指定元素不存在！ index = " << index;
        return;
    }
    SessionFriendItem* item = dynamic_cast<SessionFriendItem*>(layoutItem->widget());
    item->select();

}



SessionFriendItem::SessionFriendItem(QWidget *owner, const QIcon &avatar, const QString &name, const QString &text)
    : owner(owner)
{
    this->setFixedHeight(70);
    this->setStyleSheet("QWidget { background-color: rgb(231, 231, 231); }");

    // 创建网格布局管理器
    QGridLayout* layout = new QGridLayout();
    layout->setContentsMargins(20, 0, 0, 0);
    layout->setHorizontalSpacing(10);
    layout->setVerticalSpacing(0);
    this->setLayout(layout);

    // 创建头像
    QPushButton* avatarBtn = new QPushButton();
    avatarBtn->setFixedSize(50, 50);
    avatarBtn->setIconSize(QSize(50, 50));
    avatarBtn->setIcon(avatar);
    avatarBtn->setStyleSheet("QPushButton {border: none;}");
    avatarBtn->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);

    // 创建名字
    QLabel* nameLabel = new QLabel();
    nameLabel->setText(name);
    nameLabel->setStyleSheet("QLabel { font-size: 18px; font-weight: 600; }");
    nameLabel->setFixedHeight(35);
    nameLabel->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed);

    // 创建消息预览的 label
    messageLabel = new QLabel();
    messageLabel->setText(text);
    messageLabel->setFixedHeight(35);
    messageLabel->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed);

    // 头像处于 0, 0 位置, 占据 2 行, 占据 2 列
    layout->addWidget(avatarBtn, 0, 0, 2, 2);
    // 名字处于 0, 2 位置, 占据 1 行, 占据 1 列
    layout->addWidget(nameLabel, 0, 2, 1, 8);
    // 消息预览处于 1, 2 位置, 占据 1 行, 占据 1 列
    layout->addWidget(messageLabel, 1, 2, 1, 8);
}

void SessionFriendItem::paintEvent(QPaintEvent *event)
{
    (void) event;
    QStyleOption opt;
    opt.initFrom(this);
    QPainter p(this);
    style()->drawPrimitive(QStyle::PE_Widget, &opt, &p, this);
}

void SessionFriendItem::mousePressEvent(QMouseEvent *event)
{
    //鼠标点击时触发这个事件
    //点这个 其余元素还原背景色
    //遍历其他元素
    (void) event;
    select();
}

void SessionFriendItem::enterEvent(QEnterEvent *event)
{
    (void) event;
    if(this->selected == false)
        this->setStyleSheet("QWidget {background-color: rgb(215, 215, 215);}");
}

void SessionFriendItem::leaveEvent(QEvent *event)
{
    (void) event;
    if(this->selected == false)
        this->setStyleSheet("QWidget {background-color: rgb(231, 231, 231);}");
}

void SessionFriendItem::select()
{
    const QObjectList QObjectList = this->parentWidget()->children();
    for(QObject* child : QObjectList)
    {
        if(!child->isWidgetType())
        {
            continue;
        }
        //如果是widget 强转成 SessionFriendItem
        SessionFriendItem* item = dynamic_cast<SessionFriendItem*>(child);
        if(item->selected)
        {
            item->selected = false;
            item->setStyleSheet("QWidget {background-color: rgb(231, 231, 231);}");
        }

    }
    this->setStyleSheet("QWidget {background-color: rgb(210, 210, 210);}");
    this->selected = true;

    //调用active
    this->active();

}

void SessionFriendItem::active()
{
    //不需要实现任何逻辑
}

//////////////////////////////////////////////////////////////
///会话item的实现
//////////////////////////////////////////////////////////////
SessionItem::SessionItem(QWidget *owner, const QString &chatSessionId,
                         const QIcon &avatar, const QString &name, const QString &lastMessage)
    :SessionFriendItem(owner, avatar, name, lastMessage)
    ,chatSessionId(chatSessionId)
    ,lastMessageText(lastMessage)
{
    //处理更新最后一条消息的信号 构造时绑定
    DataCenter* dataCenter = DataCenter::getInstance();
    connect(dataCenter, &DataCenter::updateLastMessage, this, &SessionItem::updateLastMessage);

    //显示出未读消息的数目 为了支持客户端重启之后 还能显示未读消息数目
    int unreadCount = dataCenter->getUnreadCount(chatSessionId);
    if(chatSessionId == "2000")
        LOG() << "SessionItem 构造时 获取未读消息数目 chatSessionId: " << chatSessionId << " unreadCount: " << unreadCount;
    if(unreadCount > 0)
    {
        this->messageLabel->setText("[未读" + QString::number(unreadCount) + "条]" + lastMessageText);
    }

}

void SessionItem::active()
{

    LOG() << "点击sessionitem 触发的逻辑 chatSessionId:" << chatSessionId ;
    //加载最近的历史消息
    //加载历史消息的操作 既会涉及到内存数据的操作 又会涉及网络通信 还有界面变更
    MainWidget* mainwidget = MainWidget::getInstance();
    mainwidget->loadRecentMessage(chatSessionId);

    //清除未读消息的数目 并且更新显示
    DataCenter* dataCenter = DataCenter::getInstance();
    dataCenter->clearUnread(chatSessionId);

    //更新界面显示 把[未读x条消息去掉]
    this->messageLabel->setText(lastMessageText);
}

void SessionItem::updateLastMessage(const QString &chatSessionId)
{
    //30个item 就连结了30个槽函数 一个信号来了 30个都会被触发 必须指定sessionId
    if(this->chatSessionId != chatSessionId)
    {
        return;
    }
    //获取最后一条消息内容
    DataCenter* dataCenter = DataCenter::getInstance();
    QList<Message>* messageList = dataCenter->getRecentMessage(chatSessionId);
    if(messageList == nullptr || messageList->size() == 0 )
    {
        LOG() << "没有最近消息 chatSessionId:" << chatSessionId ;
        return;
    }
    const Message& lastMessage = messageList->back();
    //明确显示的文本内容 根据消息类型
    if(lastMessage.messageType == Message_Type::TEXT_TYPE)
    {
        lastMessageText = lastMessage.content;
    }
    else if(lastMessage.messageType == Message_Type::IMAGE_TYPE)
    {
        lastMessageText = "[图片消息]";
    }
    else if(lastMessage.messageType == Message_Type::FILE_TYPE)
    {
        lastMessageText = "[文件消息]";
    }
    else if(lastMessage.messageType == Message_Type::SPEECH_TYPE)
    {
        lastMessageText = "[语音消息]";
    }
    else
    {
        LOG() << "未知消息类型 chatSessionId:" << chatSessionId ;
        return;
    }

    //显示出未读消息的数目
    //先判断当前会话有没有被选中
    if(chatSessionId == dataCenter->getCurrentChatSessionId())
    {
        //当前会话被选中 清除未读消息数目
        //LOG() << "SessionItem updateLastMessage 当前会话被选中 清除未读消息数目 chatSessionId: " << chatSessionId ;
        dataCenter->clearUnread(chatSessionId);
    }

    int unreadCount = dataCenter->getUnreadCount(chatSessionId);
    if(unreadCount > 0)
    {
        this->messageLabel->setText("[未读" + QString::number(unreadCount) + "条]" + lastMessageText);
    }
    else
    {
        this->messageLabel->setText(lastMessageText);
    }

}

//////////////////////////////////////////////////////////////
///好友item的实现
//////////////////////////////////////////////////////////////
FriendItem::FriendItem(QWidget *owner, const QString &userId, const QIcon &avatar,
                       const QString &name, const QString &description)
    :SessionFriendItem(owner, avatar, name, description)
    ,userId(userId)
{

}

void FriendItem::active()
{
    //点击之后 自动跳转到对话
    LOG() << "点击sessionitem 触发的逻辑 userId:" << userId ;
    MainWidget* mainwidget = MainWidget::getInstance();

    mainwidget->switchChatSession(userId);
}

//////////////////////////////////////////////////////////////
///好友申请item的实现
//////////////////////////////////////////////////////////////
ApplyItem::ApplyItem(QWidget *owner, const QString &userId, const QIcon &avatar,
                     const QString &name)
    :SessionFriendItem(owner, avatar, name, "")
    ,userId(userId)
{
    //1.移除父类的messageLabel
    QGridLayout* layout = dynamic_cast<QGridLayout*>(this->layout());
    layout->removeWidget(messageLabel);
    delete messageLabel;

    //2.创建两个按钮
    QPushButton* acceptBtn = new QPushButton();
    acceptBtn->setText("同意");
    QPushButton* rejectBtn = new QPushButton();
    rejectBtn->setText("拒绝");
    layout->addWidget(acceptBtn, 1, 2, 1, 1);
    layout->addWidget(rejectBtn, 1, 3, 1, 1);

    //3.绑定信号槽
    connect(acceptBtn, &QPushButton::clicked, this, &ApplyItem::acceptFriendApply);
    connect(rejectBtn, &QPushButton::clicked, this, &ApplyItem::rejectFriendApply);
}

void ApplyItem::active()
{
    //TODO
    LOG() << "点击sessionitem 触发的逻辑 userId:" << userId ;
}

void ApplyItem::acceptFriendApply()
{
    //发起网络请求 同意好友申请
    DataCenter* dataCenter = DataCenter::getInstance();
    //处理槽函数在主窗口
    dataCenter->acceptFriendApplyAsync(userId);
}

void ApplyItem::rejectFriendApply()
{
    //发起网络请求 拒绝好友申请
    DataCenter* dataCenter = DataCenter::getInstance();
    //处理槽函数在主窗口
    dataCenter->rejectFriendApplyAsync(userId);
}
